<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row class="elRow">
        <el-button type="primary" @click="clickAdd">添加分类</el-button>
      </el-row>
      <!-- 数据列表 -->
      <tree-table
        :data="listInfo"
        :columns="columns"
        :selection-type="false"
        :expand-type="props.expandType"
        :show-index="props.showIndex"
        index-text="#"
        border
        :show-row-hover="props.showRowHover"
      >
        <!-- 是否有序 -->
        <template v-slot:isOk="scope">
          <i
            class="el-icon-success"
            v-show="scope.row.cat_deleted == false"
            style="color: lightgreen"
          ></i>
          <i
            class="el-icon-error"
            style="color: red"
            v-show="scope.row.cat_deleted == true"
          ></i>
        </template>
        <!-- 排序 -->
        <template v-slot:Sort="scope">
          <el-tag v-show="scope.row.cat_level == 0">一级</el-tag>
          <el-tag type="warning" v-show="scope.row.cat_level == 1">二级</el-tag>
          <el-tag type="danger" v-show="scope.row.cat_level == 2">三级</el-tag>
        </template>
        <!-- 操作 -->
        <template v-slot:Make="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            @click="editInfo(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            @click="deleteCate(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addCateClose"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="活动名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <!-- 级联选择器 -->
        <el-form-item label="父级分类:">
          <!-- options用来指定数据源 -->
          <!-- props用来指定配置对象 -->
          <!-- v-model绑定选中的值 -->
          <el-cascader
            expand-trigger="hover"
            v-model="selectedKeys"
            :options="menuInfo"
            :props="cascaderProps"
            @change="cateHandleChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分类对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editCateClose"
    >
      <el-form
        :model="editFormInfo"
        :rules="addRules"
        ref="editRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editFormInfo.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="enterEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 请求信息
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      // 存储分类列表数据
      listInfo: [],
      // 总数据条数
      total: 0,
      //为table指定列的定义  每一列都以一个新的配置对象
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",

          type: "template",
          template: "isOk",
        },
        {
          label: "排序",
          type: "template",
          template: "Sort",
        },
        {
          label: "操作",
          type: "template",
          template: "Make",
        },
      ],
      props: {
        stripe: false,
        showHeader: true,
        showSummary: false,
        showRowHover: false,
        showIndex: true,
        treeType: true,
        isFold: true,
        expandType: false,
        selectionType: false,
      },
      // 控制添加用户对话框显示
      addDialogVisible: false,
      // 添加分类表单
      addForm: {
        cat_name: "",
        // 父级分类的ID
        cat_pid: 0,
        // 分类层级
        cat_level: 0,
      },
      // 添加用户表单验证对象
      addRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      // 级联选择框数据  只需要第1,2级数据  级联选择器显示的数据
      menuInfo: [],
      // 级联选择器实际选择到的ID

      // 级联选择器配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 级联选择器选中值 ID形式
      selectedKeys: [],
      // 修改分类对话框
      editDialogVisible: false,
      // 根据ID查到的数据
      editFormInfo: { cat_name: "" },
      editId: "",
    };
  },
  created() {
    this.getData();
  },
  methods: {
    //请求分类列表数据
    async getData() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });

      if (res.meta.status != 200) {
        return this.$message.error("请求失败");
      }

      this.total = res.data.total;
      this.listInfo = res.data.result;
    },
    // 分页器页码改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getData();
    },
    // 分页器当前页改变
    handleCurrentChange(currentIndex) {
      this.queryInfo.pagenum = currentIndex;
      this.getData();
    },
    // 点击添加分类按钮
    clickAdd() {
      this.getmenuData();
      this.addDialogVisible = true;
    },
    // 获取级联选择框数据
    async getmenuData() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status != 200) {
        return this.$message.error("请求失败");
      }
      this.menuInfo = res.data;

      // console.log(res);
    },
    // 监听级联选择器变化
    cateHandleChange() {
      // 如果选中了分类
      if (this.selectedKeys.length > 0) {
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
        this.addForm.cat_level = this.selectedKeys.length;
      } else {
        this.addForm.cat_pid = 0;
        this.addForm.cat_level = 0;
      }
      console.log(this.addForm);
      console.log(this.selectedKeys);
    },
    // 点击确认
    addCate() {
      // 表单预校验
      this.$refs.addRuleForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        // 发送网络请求
        const { data: res } = await this.$http.post("categories", this.addForm);
        console.log(res);
        if (res.meta.status != 201) {
          return this.$message.error("请求出错");
        }
        this.$message.success(res.meta.msg);
        this.getData();
        this.addDialogVisible = false;
      });
    },
    // 监听对话框的关闭时间,重置表单数据
    addCateClose() {
      this.$refs.addRuleForm.resetFields();
      this.selectedKeys = [];
      this.addForm.cat_pid = 0;
      this.addForm.cat_pid = 0;
    },

    // 点击编辑按钮
    async editInfo(role) {
      this.editId = role.cat_id;
      const { data: res } = await this.$http.get(`categories/${role.cat_id}`);
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg);
      }
      this.editFormInfo = res.data;
      console.log(res);
      this.editDialogVisible = true;
    },
    // 修改用户菜单关闭
    editCateClose() {
      this.$refs.editRuleForm.resetFields();
    },
    // 点击修改用户确认按钮
    enterEdit() {
      // 先进行表单预验证
      this.$refs.editRuleForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.info("请输入修改信息");
        }
        const { data: res } = await this.$http.put(
          `categories/${this.editId}`,
          { cat_name: this.editFormInfo.cat_name }
        );
        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        this.getData();
        this.editDialogVisible = false;
      });
    },
    // 删除分类
    async deleteCate(cate) {
      // console.log(cate.cat_id);
      const ress = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (ress != "confirm") {
        return this.$message.info("取消删除");
      }
      // 发送HTTP请求
      const { data: res } = await this.$http.delete(
        `categories/${cate.cat_id}`
      );
      if (res.meta.status != 200) {
        this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getData();
      // console.log(res);
    },
  },
};
</script>

<style lang='less' scoped>
.elRow {
  margin-bottom: 20px;
}
.el-cascader {
  width: 100%;
}
</style>